// src/components/profile/OrderHistory.jsx
import React, { useEffect, useState } from 'react';
import { getItem } from '../../utils/localStorage';
import { useAuth } from '../../contexts/AuthContext';

const OrderHistory = () => {
  const [orders, setOrders] = useState([]);
  const { user } = useAuth();

  useEffect(() => {
    if (!user) return;

    const storedOrders = JSON.parse(getItem('user_orders') || '[]');
    if (storedOrders.length === 0) {
      const initialOrders = [
        {
          id: 1,
          trackName: '上海国际赛道',
          vehicleName: 'Ferrari 488 GT3',
          date: '2024-02-15',
          duration: 2,
          totalPrice: 19998,
          status: 'completed'
        },
        {
          id: 2,
          trackName: '珠海国际赛道',
          vehicleName: 'AMG GT3',
          date: '2024-03-20',
          duration: 1,
          totalPrice: 8999,
          status: 'upcoming'
        }
      ];
      setOrders(initialOrders);
    } else {
      setOrders(storedOrders);
    }
  }, [user]);

  const getStatusBadge = (status) => {
    switch (status) {
      case 'completed':
        return (
          <span className="px-2 py-1 bg-green-100 text-green-800 rounded-full text-sm">
            已完成
          </span>
        );
      case 'upcoming':
        return (
          <span className="px-2 py-1 bg-blue-100 text-blue-800 rounded-full text-sm">
            即将开始
          </span>
        );
      default:
        return (
          <span className="px-2 py-1 bg-gray-100 text-gray-800 rounded-full text-sm">
            {status}
          </span>
        );
    }
  };

  return (
    <div className="bg-white rounded-lg shadow-md overflow-hidden">
      <div className="px-6 py-4 bg-gray-50 border-b">
        <h2 className="text-xl font-semibold text-gray-900">订单历史</h2>
      </div>
      <div className="divide-y">
        {orders.map((order) => (
          <div key={order.id} className="p-6">
            <div className="flex justify-between items-start">
              <div>
                <h3 className="text-lg font-semibold text-gray-900">
                  {order.trackName}
                </h3>
                <p className="mt-1 text-gray-600">{order.vehicleName}</p>
                <div className="mt-2 text-sm text-gray-500">
                  预订日期：{order.date} · {order.duration}小时
                </div>
              </div>
              <div className="text-right">
                <div className="text-lg font-semibold text-blue-600">
                  ¥{order.totalPrice}
                </div>
                <div className="mt-2">{getStatusBadge(order.status)}</div>
              </div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
};

export default OrderHistory;